// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

// let env = window.wx || window.tt || window.swan;
// env && env.onMessage(res => {
//     console.log('message form mainproject')
//     if (!res.fromEngine) {
//         console.log('Message recieved: ', res.value);
//     }
// });



const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

  @property({type: cc.Prefab})
  itemPrefab: cc.Prefab = null;

  @property({type: cc.Node})
  scrollViewContent: cc.Node = null;

  msg:any = null
  myname = null
  onLoad () {
    this.spawnItems();
    var self = this
    if(cc.sys.platform != cc.sys.WECHAT_GAME_SUB) return 
    //@ts-ignore
    wx.onMessage((msg: any) => this.onMessage(msg));
    //@ts-ignore
    this.getRank()
  }

  protected onEnable(): void {
    // if(this.myname){

    // }
  }

  spawnItems () {
    for (let i = 0; i < 10; ++i) {
        let item = cc.instantiate(this.itemPrefab);
        item.name = `item_${i}`;
        item.active = !1
        this.scrollViewContent.addChild(item);
    }
  }  

  private onMessage(msg:any){
    console.log('主域通信数据',msg)
    switch(msg.event){
      case 'getRank':
        this.msg = msg
        this.myname = this.msg.name
        //@ts-ignore

        //this.getRank()
      break
      // case 'setuserinfo':
      //   this.setUserInfo(msg)
      // break
    }
  }
  
  
  private async getRank(){
    await new Promise<void>(resolve =>{
      //@ts-ignore
      wx.getFriendCloudStorage({
        keyList: ['checkout'],
        success:(res:any)=>{
          console.log('[getRank]', 'success', res);
          resolve();
          this.updateRankUi(res)
        },
        fail:(res)=>{
          console.log('[getRank]', 'fail');
          resolve();
        }
      })
    })
  }

  updateRankUi(data:any){
    function compare(a, b) {
        if(b.KVDataList.length>0 && a.KVDataList.length>0){
            return Number(b.KVDataList[0].value)  - Number(a.KVDataList[0].value) ;
        }
        else{
          return 0
        } 
          
    }
    let arr = data.data.sort(compare);
    console.log('排序后', arr)

    let count = Math.max(this.scrollViewContent.childrenCount, data.data.length)
    if(count<=0){
      //this.note.active = !0
    }
  
    for(let i= 0; i< count ; i++){
      console.log('打印创建节点', i)
      if(this.scrollViewContent.children[i] && data.data[i]){
        //已存在的节点，更新
        this.scrollViewContent.children[i].active = !0
        this.setItem(i,this.scrollViewContent.children[i], data.data[i])
      }
      else if(data.data[i] && !this.scrollViewContent.children[i]){
        //不存在，加一个
        let newnode = cc.instantiate(this.itemPrefab)
        this.scrollViewContent.addChild(newnode)
        this.setItem(i,newnode, data.data[i])
      }
      else{
        //多余，关闭
        this.scrollViewContent.children[i].active = !1
      }
    }
  }


  setItem(no:number,node, data){
    let item = node
    let nostr = cc.find('no', item).getComponent(cc.Label)
    nostr.string = ''+(no+1)
    switch(no){
      case 0:
        nostr.node.color = cc.Color.RED
      break
      case 1:
        nostr.node.color = cc.Color.BLUE
        break
      case 2:
        nostr.node.color = cc.Color.GREEN
        break
      default :
        nostr.node.color = cc.color(87,87,87,255)
        break
    }
    let icon = cc.find('icon', item).getComponent(cc.Sprite)
    let url = data.avatarUrl
    //@ts-ignore
    let image = wx.createImage();
    image.onload = () => {
        let texture = new cc.Texture2D();
        texture.initWithElement(image);
        texture.handleLoadedTexture();
        icon.spriteFrame = new cc.SpriteFrame(texture);
    };
    image.src = url;

    let name = cc.find('name', item).getComponent(cc.Label)
    name.string = ''+data.nickname
    let fen = cc.find('fen', item).getComponent(cc.Label)

    if(data.KVDataList[0]){
      fen.string = ''+data.KVDataList[0].value + '关'
    }else{
      fen.string = '0关'
    }
  }
}
